#!/usr/bin/env node

const path = require("path");
// const fs = require("fs");

const async = require("async");
const Epub = require("epub-gen");

const dispatchEmail = require("./mailToKindle");
const NprProcessListFn = require("./news-npr");
const HuxiuProcessListFn = require("./news-huxiu");

// waterfall的最后两道流程
let tasks = [
  ({ option, name }, cb) => {
    let output = path.resolve(__dirname, "epub", name);
    new Epub(option, output).promise.then(
      () => cb(null, output),
      (error) => cb(error)
    );
  },
  (output, cb) => {
    console.log("邮件即将发送: " + output);
    dispatchEmail(output)
      .then((info) => cb(null))
      .catch((error) => cb(error));
  },
];

// 默认获取npr的新闻信息
function spider(source = "npr", cb) {
  let fn = {
    npr: NprProcessListFn,
    huxiu: HuxiuProcessListFn,
  }[source];
  async.waterfall([...fn, ...tasks], cb);
}

module.exports = spider;
